package top.kaoshanji.v1ch13a.services;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.kaoshanji.v1ch13a.model.Account;
import top.kaoshanji.v1ch13a.repositories.AccountRepository;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author kaoshanji
 * ^_^
 * create time 2025/5/1 18:11
 */
@Service
public class TransferService {

    private final AccountRepository accountRepository;

    public TransferService(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    /**
     * 代码清单-v1ch13a-268页a：使用@Transactional指示Spring把方法的调用封装在事务中
     * 代码清单-v1ch13a-272页a：如果抛出异常，那么事务就回滚了
     * @param idSender
     * @param idReceiver
     * @param amount
     */
    @Transactional
    public void transferMoney(long idSender, long idReceiver, BigDecimal amount) {
        Account sender = accountRepository.findAccountById(idSender);
        Account receiver = accountRepository.findAccountById(idReceiver);

        BigDecimal senderNewAmount = sender.getAmount().subtract(amount);
        BigDecimal receiverNewAmount = receiver.getAmount().add(amount);

        accountRepository.changeAmount(idSender, senderNewAmount);
        accountRepository.changeAmount(idReceiver, receiverNewAmount);

        // 先注释掉，运行一下，数据库数据发生了变化...正常
        // 然后去掉注释，再运行一下...数据库数据没有发生变化
        // throw new RuntimeException("No..No..No..No..");
    }

    public List<Account> getAllAccounts() {
        return accountRepository.findAllAccounts();
    }

}
